/**
 * 
 */
package com.antilia.infomaresme.data.dataobjects;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

/**
 * @author Ernesto
 *
 */
@Entity
@Table(uniqueConstraints = {@UniqueConstraint(columnNames={"user_fk","item_fk"})})
public class UserItemAlert extends DomainObject {

	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue
	private Long id;
	
	@ManyToOne(fetch = FetchType.EAGER)
	@JoinColumn(name="user_fk")
	private User user;
	
	/**
	 * A tes to make easy to indetyfy the alert.
	 */
	private String title;
	
	@ManyToOne(fetch = FetchType.EAGER)
	@JoinColumn(name="item_fk")
	private Item item;
	
	/**
	 * List of event to monitor.
	 */
	@Column(nullable=false)
	private String events;
	
	@Column(nullable=false)
	private Frequency emailFrequency;
	
	/**
	 * 
	 */
	public UserItemAlert() {
		// TODO Auto-generated constructor stub
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public Item getItem() {
		return item;
	}

	public void setItem(Item item) {
		this.item = item;
	}

	public String getEvents() {
		return events;
	}

	public void setEvents(String events) {
		this.events = events;
	}
	
	public void setEvents(List<ItemEventSubject> events) {
		if(events == null || events.size() == 0) {			
			this.events = null;
			return;
		}
		StringBuilder sb  = new StringBuilder();
		for(ItemEventSubject event: events) {
			sb.append(event.name());
			sb.append(",");
		}
		this.events = sb.toString();
	}
	
	public List<ItemEventSubject> getEventsAsEnum() {
		if(events != null) {
			List<ItemEventSubject> eventSubjects = new ArrayList<ItemEventSubject>();
			String[] sev = events.split(",");
			for(String  string: sev) {
				try {
					eventSubjects.add(ItemEventSubject.valueOf(string));
				} catch (Exception e) {
					
				}
			}
			return eventSubjects;
		}
		return null;
	}

	public Frequency getEmailFrequency() {
		return emailFrequency;
	}

	public void setEmailFrequency(Frequency emailFrequency) {
		this.emailFrequency = emailFrequency;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

}
